/**
 * 
 */
package com.attilax.db;

import com.attilax.core;
import com.attilax.io.filex;
import com.attilax.io.pathx;
//import com.attilax.lang.json.JsonX;
import com.attilax.lang.text.strUtil;
import com.opensymphony.xwork2.inject.Inject;

/**
 * @author ASIMO
 * 
 */
public class Mssql2MysqlConvertor {

	@Inject
	SqlAstBuilderP32 astBldr;
	SqlAstP32 ast;

	/**
	 * @author attilax 老哇的爪子
	 * @since p33 j_t_37
	 */
	public static void main(String[] args) {
		String txt = filex.read(pathx.classPath() + "/mssql1.sql");
		txt = strUtil.replaceEnterChar2space(txt);
	

		Mssql2MysqlConvertor x = new Mssql2MysqlConvertor();
		String sql_mysql = x.convert(txt);

	//	System.out.println(JsonX.toJsonStrO88(x.ast));
		System.out.println(sql_mysql);

	}

	/**
	 * @author attilax 老哇的爪子
	 * @return
	 * @since p33 m_j_45
	 */
public	  String convert(String txt) {
		txt = txt.replaceAll("row_number.*?,", "");
		String page_s = strUtil.find("rowNum(.+)BETWEEN.+and.+$", txt).get(0)
				.toString();
		page_s = strUtil.replaceDoubleSpace(page_s);
		String[] a = page_s.toUpperCase().trim().split("BETWEEN");
		String[] a2 = a[1].toLowerCase().trim().split("and");
		SqlPageParam p = new SqlPageParam();
		p.startIndex = Integer.parseInt(a2[0].trim()) - 1;
		p.pagesize = Integer.parseInt(a2[1].trim());
		ast = new SqlAstP32();
		ast.preOther = txt.substring(0, txt.indexOf(page_s));
		ast.pagePart = p;
		if (ast.preOther.trim().toLowerCase().endsWith("where"))
			ast.preOther = ast.preOther + " 1=1 ";
		return ast.preOther + " limit " + p.startIndex + "," + p.pagesize;

	}

}
